package com.jcfk.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.controller.BaseController;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.log.annotation.RequestLogHeader;
import com.jcfk.common.business.utils.DataBindHelper;
import com.jcfk.common.security.annotation.AllowAnonymous;
import com.jcfk.common.web.domain.*;
import com.jcfk.system.domain.dto.SysDictionaryDTO;
import com.jcfk.system.domain.dto.SysDictionaryItemDTO;
import com.jcfk.system.domain.po.SysDictionary;
import com.jcfk.system.domain.query.SysDictionaryItemQuery;
import com.jcfk.system.domain.query.SysDictionaryQuery;
import com.jcfk.system.service.SysDictionaryItemService;
import com.jcfk.system.service.SysDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典管理 服务接口
 *
 * @author 李炳海
 * @date 2023-11-2
 */
@Api(tags = "字典管理", description = "字典管理")
@RestController
@RequestMapping("/dictionary")
public class SysDictionaryController extends BaseController {
    @Autowired
    private SysDictionaryService sysDictionaryService;
    @Autowired
    private SysDictionaryItemService sysDictionaryItemService;

    /**
     * 获取字典列表
     *
     * @return
     */
    @PostMapping("getDictionarys")
    public RetResult<List<SysDictionaryDTO>> getDictionarys() {
        return RetResult.ok(sysDictionaryService.getList());
    }

    /**
     * 查询字典项(分页)
     *
     * @param requestParam
     * @return
     */
    @PostMapping("queryItemPage")
    public RetPage<SysDictionaryItemDTO> queryItemPage(@RequestBody ReqPageParam<SysDictionaryItemQuery> requestParam) {
        DataPage<SysDictionaryItemDTO> page = new DataPage<SysDictionaryItemDTO>((long) requestParam.getCurrent(), (long) requestParam.getSize(), requestParam.getSort().getOrderItem(), SysDictionaryItemDTO.class);
        page = sysDictionaryItemService.queryByPage(page, requestParam.getData());

        // 绑定启用标志文本
        DataBindHelper.bindDataLabel(page.getRecords(), AvailableStatus.getMap(), "enabled", "enabledLabel");

        return new RetPage(page);
    }

    /**
     * 查询字典项(分页)
     *
     * @param requestParam
     * @return
     */
    @ApiOperation("字典名称分页")
    @PostMapping("queryPage")
    public RetPage<SysDictionaryDTO> queryPage(@RequestBody ReqPageParam<SysDictionaryQuery> requestParam) {
        DataPage<SysDictionaryDTO> page = new DataPage((long) requestParam.getCurrent(), (long) requestParam.getSize(), requestParam.getSort().getOrderItem(), SysDictionaryDTO.class);
        page = sysDictionaryService.queryByPage(page, requestParam.getData());

        // 绑定启用标志文本
        DataBindHelper.bindDataLabel(page.getRecords(), AvailableStatus.getMap(), "enabled", "enabledLabel");

        return new RetPage(page);
    }

    /**
     * 获取字典项
     *
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    public RetResult<SysDictionaryItemDTO> get(@PathVariable("id") String id) {
        return RetResult.ok(sysDictionaryItemService.get(id));
    }

    /**
     * 保存字典项值
     *
     * @param sysDictionaryItem
     * @return
     */
    @ApiOperation("保存字典值")
    @RequestLogHeader(modular = "字典管理", businessType = "保存")
    @PostMapping("saveItem")
    public RetResult<SysDictionaryItemDTO> saveItem(@RequestBody @Validated SysDictionaryItemDTO sysDictionaryItem) {
        // 数据校验
        RetResult ret = sysDictionaryItemService.isValid(sysDictionaryItem);
        if (!ret.getCode().equals(RetResult.SUCCESS)) {
            return ret;
        }

        if (StrUtil.isEmpty(sysDictionaryItem.getId())) {
            // 新增
            return RetResult.ok(sysDictionaryItemService.insert(sysDictionaryItem));
        } else {
            // 更新
            return RetResult.ok(sysDictionaryItemService.update(sysDictionaryItem));
        }

    }

    /**
     * 保存字典名称
     *
     * @param dto
     * @return
     */
    @ApiOperation("添加修改字典名称")
    @RequestLogHeader(modular = "添加修改字典名称", businessType = "保存")
    @PostMapping("save")
    public RetResult<SysDictionaryDTO> save(@RequestBody @Validated SysDictionaryDTO dto) {
        // 数据校验
        RetResult ret = sysDictionaryService.isValid(dto);
        if (!ret.getCode().equals(RetResult.SUCCESS)) {
            return ret;
        }

        if (StrUtil.isEmpty(dto.getId())) {
            // 新增
            return RetResult.ok(sysDictionaryService.insert(dto));
        } else {
            // 更新
            return RetResult.ok(sysDictionaryService.update(dto));
        }

    }


    /**
     * 删除字典项
     *
     * @param dto
     * @return
     */
    @ApiOperation("删除字典名称")
    @RequestLogHeader(modular = "字典管理", businessType = "删除")
    @PostMapping("deleteList")
    public RetResult<String> deleteList(@RequestBody SysDictionaryDTO dto) {
        sysDictionaryService.logicDeleteList(dto);
        return RetResult.ok();
    }

    /**
     * 删除字典项
     *
     * @param dto
     * @return
     */
    @RequestLogHeader(modular = "字典管理", businessType = "删除")
    @PostMapping("deleteItemList")
    public RetResult<String> deleteItemList(@RequestBody SysDictionaryItemDTO dto) {
        sysDictionaryItemService.logicDeleteList(dto);
        return RetResult.ok();
    }

    /**
     * 删除字典项
     *
     * @param sysDictionaryItem
     * @return
     */
    @RequestLogHeader(modular = "字典管理", businessType = "删除")
    @PostMapping("deleteItem")
    public RetResult<String> deleteItem(@RequestBody SysDictionaryItemDTO sysDictionaryItem) {
        sysDictionaryItemService.logicDelete(sysDictionaryItem);
        return RetResult.ok();
    }


    /**
     * 获取字典项列表
     *
     * @param query
     * @return
     */
    @AllowAnonymous
    @PostMapping("getDictionaryItems")
    public RetResult<List<SysDictionaryItemDTO>> getDictionaryItems(@RequestBody SysDictionaryItemQuery query) {
        return RetResult.ok(sysDictionaryItemService.getListByCache(query.getDictionaryCode()));
    }

    /**
     * 获取全部字典项列表
     *
     * @param query
     * @return
     */
    @AllowAnonymous
    @PostMapping("getAllDictionaryItems")
    public RetResult<Map<String, List<Map<String, String>>>> getAllDictionaryItems(@RequestBody SysDictionaryItemQuery query) {
        List<SysDictionaryItemDTO> list = sysDictionaryItemService.getList(query);
        Map<String, List<Map<String, String>>> resultMap = list.stream().collect(Collectors.groupingBy(SysDictionaryItemDTO::getDictionaryCode, Collectors.mapping(item -> {
            Map<String, String> map = new HashMap<>();
            map.put("label", item.getItemLabel());
            map.put("value", item.getItemValue());
            return map;
        }, Collectors.toList())));
        return RetResult.ok(resultMap);
    }

    /**
     * 获取字典项集合
     *
     * @param query
     * @return
     */
    @AllowAnonymous
    @PostMapping("getDictionaryItemMaps")
    public RetResult<Map<String, String>> getDictionaryItemMaps(@RequestBody SysDictionaryItemQuery query) {
        List<SysDictionaryItemDTO> list = sysDictionaryItemService.getListByCache(query.getDictionaryCode());
        Map<String, String> maps = list.stream().collect(Collectors.toMap(SysDictionaryItemDTO::getItemValue, SysDictionaryItemDTO::getItemLabel, (key1, key2) -> key2));

        return RetResult.ok(maps);
    }

    /**
     * 获取组合控件数据项结合
     *
     * @param code
     * @return
     */
    @PostMapping("getSelectedItems/{code}")
    public RetResult<List<SelectItem>> getSelectItems(@PathVariable(name = "code") String code) {
        SysDictionaryItemQuery query = new SysDictionaryItemQuery();
        query.setDictionaryCode(code);
        List<SysDictionaryItemDTO> dis = sysDictionaryItemService.getList(query);

        return RetResult.ok(dis.stream().sorted(Comparator.comparing(p -> p.getSort())).map(p -> {
            SelectItem item = new SelectItem();

            item.setLabel(p.getItemLabel());
            item.setValue(p.getItemValue());

            return item;
        }).collect(Collectors.toList()));
    }
}
